package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
@Component
@ResponseBody
@RestControllerAdvice
public class CommonExceptionHandler {

    /**
     * 异常处理方法
     * @param e
     * @return
     */
    //DuplicateKeyException
    // SQLIntegrityConstraintViolationException
    @ExceptionHandler(DuplicateKeyException.class)
    public R handlerException(SQLIntegrityConstraintViolationException e) {
        log.error(e.getMessage());
        // 账号 xxx 已存在!!     SQLIntegrityConstraintViolationException
        String message = e.getMessage();
        // Duplicate entry 'xxx' for key 'username'
        String[] split = message.split("'");
        String msg = "账号" + split[1] + "已存在!!";
        return R.error(msg);
    }

    @ExceptionHandler(CustomException.class)
    public R exceptionHandler(CustomException e) {
        log.error(e.getMessage());
        String message = e.getMessage();
        return R.error(message);
        //log.error(e.getMessage());
    }

    //处理异常,指定处理哪一类异常: 处理所有的Exception
    @ExceptionHandler(Exception.class)
    public R handlerException(Exception e) {
        e.printStackTrace();
        String message = e.getMessage();
        return R.error(message);
    }
}
